package cn.hunqing.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.druid.util.StringUtils;

import cn.hunqing.web.msg.RegisterMsgs;
import cn.hunqing.web.param.RegisterParameters;
import cn.hunqing.web.service.UserService;
import cn.hunqing.web.util.PathConstants;
import cn.hunqing.web.util.ViewConstants;

/**
 * add the redirect method
 * 
 * @date 2015-07-27 21:12
 */
@Controller
@RequestMapping(PathConstants.PATH_REGISTER)
public class RegisterController {
	private static Logger logger = LoggerFactory.getLogger(RegisterController.class);

	@Autowired
	private UserService userService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String doGet(HttpServletRequest request, HttpSession httpSession) {
		logger.info("Get the register page request");
		return ViewConstants.VIEW_REGISTER;
	}

	@RequestMapping(method=RequestMethod.POST)
	public String doPost(HttpServletRequest request, HttpSession httpSession, ModelMap model) {
		String userName = request.getParameter(RegisterParameters.REQUEST_USERNAME);
		String password = request.getParameter(RegisterParameters.REQUEST_PASSWORD);
		String confirmedPassword = request.getParameter(RegisterParameters.REQUEST_CONFIRMEDPASSWORD);
		logger.info("register with the userName:{}",userName);

		model.addAttribute(RegisterParameters.REQUEST_USERNAME, userName);
		model.addAttribute(RegisterParameters.REQUEST_PASSWORD, password);
		model.addAttribute(RegisterParameters.REQUEST_CONFIRMEDPASSWORD, confirmedPassword);
		
		if(StringUtils.isEmpty(userName)){
			model.addAttribute(RegisterParameters.RESPONSE_ERROR_MSG, RegisterMsgs.EMPTY_USERNAME);
			return ViewConstants.VIEW_REGISTER;
		}
		if(StringUtils.isEmpty(password)){
			model.addAttribute(RegisterParameters.RESPONSE_ERROR_MSG, RegisterMsgs.EMPTY_PASSWORD);
			return ViewConstants.VIEW_REGISTER;
		}
		if(!StringUtils.equals(password, confirmedPassword)){
			model.addAttribute(RegisterParameters.RESPONSE_ERROR_MSG, RegisterMsgs.WRONG_CONFIRMED_PASSWORD);
			return ViewConstants.VIEW_REGISTER;
		}else{
			try{
				userService.register(userName,password);
			}catch(Throwable e){
				logger.error("Get the exception when register user:"+userName, e);
				model.addAttribute(RegisterParameters.RESPONSE_ERROR_MSG, e.getMessage());
				return ViewConstants.VIEW_REGISTER;
			}
		}
		return ViewConstants.VIEW_LOGIN;
	}

}
